<?php
/**
 * ZView
 *
 * Zend Frameworks View Component for TYPO3
 *
 * @package    ZView
 * @copyright  Copyright (c) Zephir AG, www.zephir.ch
 */

/** Abstract class for extension */
require_once 'Zend/View/Helper/HtmlElement.php';


/**
 * Helper to generate a "table" element
 *
 * @package ZView
 * @copyright  Copyright (c) Zephir AG, www.zephir.ch
 */
class Tx_Zview_Helper_T3table extends Zend_View_Helper_HtmlElement
{

	private $_rowset;
	private $_columns;
	private $_fields;
	private $_attribs;
	private $_isObject;

	/**
	 * Generates a "table" element
	 *
	 * @param Iterator|array $rowset
	 * @param array $columns
	 * @param array $fields
	 * @param array $attribs
	 * @return string
	 */
    public function t3table($rowset, array $columns, array $fields, array $attribs=array())
    {

		$this->_rowset = $rowset;
		$this->_columns = $columns;
		$this->_fields = $fields;
		$this->_attribs = $attribs;
		$this->_isObject = $rowset instanceof Iterator;

		// Das Objekt wird an das Viewscript zurueckgegeben.
		// Das Viewscript gibt dieses via echo aus, dabi wird
		// die __toString() Methode aufgerufen.
		return $this;

    }

	/**
	 * The magic "to string" method
	 *
	 * @return string The generated "table" element
	 */
    private function __toString()
    {

    	$html = '';

    	// Table
    	$html .= '<table';
    	$html .= $this->_htmlAttribs($this->_attribs);
    	$html .= '>';

    	// Head
    	$html .= '<thead>';
    	$html .= '<tr>';
		foreach($this->_columns AS $column) {
			$label = isset($column['label']) ? $column['label'] : '';
			$html .= sprintf('<th>%s</th>', $label);
		}
    	$html .= '</tr>';
    	$html .= '</thead>';

    	// Body
    	$i = 0;
    	$html .= '<tbody>';
    	foreach($this->_rowset AS $row) {
    		$show = true;
    		if($show) {
	    		$class = ($i % 2 == 0) ? ' class="even"' : ' class="odd"';
		    	$html .= '<tr' . $class . '>';
				foreach($this->_fields AS $field) {
					$key = $field['key'];
					$callback = isset($field['callback']) ? $field['callback'] : '';
					if(empty($callback)) {
						if($this->_isObject) {
							$value = $row->$key;
						} else {
							// SimpleXMLElement
							if(is_object($row)) {
								$value = $row->$key;
							} else {
								$value = $row[$key];
							}
						}
					} else {
						$value = call_user_func_array($callback, array($row));
					}
					$html .= sprintf('<td>%s</td>', $value);
				}
		    	$html .= '</tr>';
		    	$i++;
    		}
    	}
    	$html .= '</tbody>';

    	// Table
    	$html .= '</table>';

    	return $html;

    }

}

if (defined('TYPO3_MODE') && $TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['ext/zview/helper/T3table.php']) {
	include_once($TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['ext/zview/helper/T3table.php']);
}
